package com.probiz.estore.catalog.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.probiz.estore.Constants;
import com.probiz.estore.catalog.dao.ContentCategoryDao;
import com.probiz.estore.catalog.model.ContentCategoryFullyModel;
import com.probiz.estore.catalog.model.ContentCategorySearchCriteria;
import com.probiz.estore.catalog.service.ContentCategoryManager;
import com.probiz.estore.catalog.util.CatalogCodeGenerator;
import com.probiz.estore.common.model.catalog.ContentCategory;
import com.probiz.estore.content.service.ContentManager;
import com.probiz.estore.content.service.RelatedContentManager;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.I18nUtil;


/**
 * Manager implementation for ContentCategory, responsible for business processing, and communicate between web and persistence layer.
 */
public class ContentCategoryManagerImpl extends BaseCategoryManagerImpl<ContentCategory> implements ContentCategoryManager {

    private ContentCategoryDao contentCategoryDao = null;
    private ContentManager contentManager = null;
    private RelatedContentManager relatedContentManager = null;

    /**
     * @param contentCategoryDao the contentCategoryDao to set
     */
    public void setContentCategoryDao(ContentCategoryDao contentCategoryDao) {
        this.contentCategoryDao = contentCategoryDao;
    }

    public void setContentManager(ContentManager contentManager) {
        this.contentManager = contentManager;
    }
    

    public void setRelatedContentManager(RelatedContentManager relatedContentManager) {
		this.relatedContentManager = relatedContentManager;
	}

	/*
      * (non-Javadoc)
      *
      * @see com.probiz.estore.core.service.impl.GenericManagerImpl#init()
      */
    @Override
    protected void initManager() {
        dao = contentCategoryDao;
        categoryDao = contentCategoryDao;
    }

    /*
      * (non-Javadoc)
      *
      * @see com.probiz.estore.core.service.impl.GenericManagerImpl#onDelete(java.lang.Object)
      */
    @Override
    protected void preDelete(ContentCategory entity) {

    }

    /*
      * (non-Javadoc)
      *
      * @see com.probiz.estore.core.service.impl.GenericManagerImpl#onSave(java.lang.Object)
      */
    @Override
    protected void preSave(ContentCategory entity) {

    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#saveFully(com.probiz.estore.catalog.model.ContentCategory)
      */

    public Map<String, Object>  saveFully(ContentCategoryFullyModel model){
    	ContentCategory category = model.getContentCategory();
    	Map<String, Object> returnMsgs = new HashMap<String, Object>();
    	
    	 //start:设置目录编码并检查
		if(StringUtils.isBlank(category.getCategoryCode())){
			boolean isCodeAvailable = false;
			do{
				String code = CatalogCodeGenerator.generateProductCategoryCode();
				Long size = contentCategoryDao.getSizeByCategoryCodeByNotCategoryId(code, category.getCategoryId());
				if(size==0){
					//该编码可用
					isCodeAvailable = true;
					category.setCategoryCode(code);
				}
			}while(!isCodeAvailable);
		}else{
			//用getSizeByCategoryCodeByNotCategoryId而不用getByCode的原因在于调用后者的时候会有update操作，造成数据库有两个相同code的商品，出错
			Long size = contentCategoryDao.getSizeByCategoryCodeByNotCategoryId(category.getCategoryCode(), category.getCategoryId());
			
			if(size>=1){
				//编码重复
				returnMsgs.put("error", I18nUtil.getInstance().getMessage("contentCategory.categoryCode.repeated"));
				evict(category); //必须把evict出session 否则会有update操作
				return returnMsgs;
			}
		}
		//end:设置目录编码并检查
		
		
    	// start:新增赋值
        if (null == category.getCategoryId()) {
            // case:新增
            ContentCategory parent = contentCategoryDao.getById(category
                    .getParentId());
            category.setDepth((short) (parent.getDepth() + 1));
            category.setItemCount(0);
            category.setActiveItemCount(0);
            category.setParentPath(parent.getCategoryPath());
            category.setCategoryPath("");//临时,必须等categoryId出来后才能再次保存
            category.setHasChildren(Constants.FLAG_FALSE);
            category.setSortOrder(ContentCategory.SORTORDER_DEFAULT_VALUE);
            // 保存父亲
            parent.setHasChildren(Constants.FLAG_TRUE);
            contentCategoryDao.save(parent);
            
            contentCategoryDao.save(category);
            // start:保存categoryPath	
            category.setCategoryPath(parent.getCategoryPath()+category.getCategoryId()+".");
            contentCategoryDao.save(category);
            // end:保存categoryPath	
        }
        // end:新增赋值
        
        // start:关联文章
		relatedContentManager.saveRelatedContentsFromArrays(null, category, model.getRelatedTypeIds(), model.getRelatedContentIds());
		// end:关联文章
		
        this.save(category);
        return returnMsgs;
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#deleteFully(com.probiz.estore.catalog.model.ContentCategory)
      */
    public Map<String, Object> deleteFully(ContentCategory category) {
        Map<String, Object> returnMsgs = new HashMap<String, Object>();
    	
    	returnMsgs.put("categoryId", category.getCategoryId());
    	if (category.getCategoryId() == 1) {
            // case:如果是根目录
    		returnMsgs.put("result", -1);
    		returnMsgs.put("message", I18nUtil.getInstance().getMessage("contentCategory.del.root"));
        } else if (!countSubCategoryById(category.getCategoryId()).equals(new Integer("0"))) {
            // case:如果包含子目录
        	returnMsgs.put("result", -2);
        	returnMsgs
                    .put("message",I18nUtil.getInstance().getMessage("contentCategory.del.containSubCat"));
        } else if (!contentManager.countContentByCategoryId(category.getCategoryId()).equals(
                new Integer("0"))) {
            // case:如果包含文章
        	returnMsgs.put("result", -3);
        	returnMsgs.put("message",I18nUtil.getInstance().getMessage("contentCategory.del.containContent"));
        } else {
            // otherwise:成功删除
           
            // 获得父id
            Integer parentId = category.getParentId();
            ContentCategory parent = contentCategoryDao.getById(category.getParentId());
            Integer subCategoryCount = contentCategoryDao.countSubCategoryById(parent.getCategoryId());
            if (subCategoryCount.compareTo(new Integer("1")) <= 0) {
                parent.setHasChildren(Constants.FLAG_FALSE);
                contentCategoryDao.save(parent);
            }
            contentCategoryDao.delete(category);
            returnMsgs.put("result", 1);
            returnMsgs.put("message", I18nUtil.getInstance().getMessage("contentCategory.del.success"));
            returnMsgs.put("parentId", parentId);
        }
    	
		return returnMsgs;

    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#getCategoryByCode(java.lang.String)
      */
    public ContentCategory getCategoryByCode(String categoryCode) {
        return contentCategoryDao.getCategoryByCode(categoryCode);
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#searchByCriteria(com.probiz.estore.catalog.model.ContentCategorySearchCriteria, com.probiz.estore.core.search.SearchCriteria)
      */
    public List<ContentCategory> searchByCriteria(ContentCategorySearchCriteria contentCategorySearchCriteria, SearchCriteria searchCriteria) {
        return contentCategoryDao.searchByCriteria(
                contentCategorySearchCriteria, searchCriteria);
    }
    
    public String getSecondLevelContentCatelogCode(Integer contentCatelogId){
    	ContentCategory contentCategory = this.getById(contentCatelogId);
    	return this.getSecondLevelContentCatelogCode(contentCategory);
    	
    }
    
    public String getSecondLevelContentCatelogCode(ContentCategory contentCategory){
    	String  categoryPath = contentCategory.getCategoryPath();
    	
    	if(null == categoryPath)return contentCategory.getCategoryCode();
    	
    	String[] categoryPathIds = categoryPath.split("\\.");
    	if(null != categoryPathIds && categoryPathIds.length > 1 ){
    		ContentCategory secondLevel = this.getById(new Integer(categoryPathIds[1]));
    		return secondLevel.getCategoryCode();
    	}else{
    		return contentCategory.getCategoryCode();
    	}
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#convertListToJSONArray(java.util.List)
      */
    public JSONArray convertListToJSONArray(List<ContentCategory> categoryList) {
        JSONArray categoryArray = new JSONArray();
        for (ContentCategory category : categoryList) {
            JSONObject categoryJSON = new JSONObject();
            categoryJSON.put("categoryId", category.getCategoryId());
            categoryJSON.put("categoryCode", category.getCategoryCode());
            categoryJSON.put("categoryName", category.getCategoryName());
            categoryJSON.put("depth", category.getDepth());
            categoryJSON.put("hasChildren", category.getHasChildren());
            categoryJSON.put("parentId", category.getParentId());
            categoryJSON.put("categoryPath", category.getCategoryPath());
            categoryJSON.put("simpleCategoryPathName", category
                    .getSimpleCategoryPathName());
            categoryJSON.put("itemCount", category.getItemCount());
            categoryJSON.put("activeItemCount", category.getActiveItemCount());
            categoryArray.add(categoryJSON);
        }
        return categoryArray;
    }


    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#getCategoryIdByUri(java.lang.String)
      */
    public Integer getCategoryIdByUri(String uri) {
        String categoryId = uri.substring(uri.lastIndexOf("cat"), uri
                .lastIndexOf("."));
        categoryId = categoryId.substring("cat".length());
        return Integer.valueOf(categoryId);
        
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#getUriByCategoryId(java.lang.Integer)
      */
    public String getUriByCategoryId(Integer categoryId) {
        StringBuffer url = new StringBuffer();
        url.append("/cms");
        for (ContentCategory contentCategory : contentCategoryDao.getNavigationCategories(categoryId)) {
            url.append("-");
            url.append(contentCategory.getCategoryCode());
        }
        url.append("/cat");
        url.append(categoryId.toString());
        url.append(".html");
        return url.toString();
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.catalog.service.ContentCategoryManager#getNavigationCategories(java.lang.Integer)
      */
    public List<ContentCategory> getNavigationCategories(Integer categoryId) {
        return contentCategoryDao.getNavigationCategories(categoryId);
	}
}
